//
//  CustomPhotoViewController.m
//  FaceRecognition
//
//  Created by zz on 16/12/2.
//  Copyright © 2016年 Sylar. All rights reserved.
//

#import "CustomPhotoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "PhotoResultViewController.h"
#import "UploadPhotoViewController.h"
@interface CustomPhotoViewController ()<CustomPhotoViewDelegate>

/**捕获设备*/
@property (nonatomic,strong) AVCaptureDevice *device;

/**输入设备*/
@property (nonatomic,strong) AVCaptureDeviceInput *input;

/**输出图片*/
@property (nonatomic,strong) AVCaptureStillImageOutput *imageOutput;

/**由它把输入输出设备结合在一起，并开始启动捕获设备*/
@property (nonatomic,strong) AVCaptureSession *session;

/**预览图层*/
@property (nonatomic,strong) AVCaptureVideoPreviewLayer * previewLayer;

/**焦点view*/
@property (nonatomic) UIView *focusView;

@end

@implementation CustomPhotoViewController

#pragma mark -Getter
- (UIView *)focusView{
    
    if (_focusView == nil) {
        
        _focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
        _focusView.layer.borderWidth = 1.0;
        _focusView.layer.borderColor =[UIColor greenColor].CGColor;
        _focusView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_focusView];
        _focusView.hidden = YES;
    }
    
    return _focusView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置相机
    [self setupCamera];
    
    _customPhotoView = [[CustomPhotoView alloc] initWithFrame:self.view.bounds];
    //delegate在此传递过去
    _customPhotoView.delegate = self.delegate;
    _customPhotoView.cameraDelegate = self;
    [self.view addSubview:_customPhotoView];
    self.view.backgroundColor = [UIColor clearColor];
    
    //点击手势
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusGesture:)];
    [self.view addGestureRecognizer:tapGesture];
}

- (void)setupCamera{
    
    self.device = [self camearWithPosition:AVCaptureDevicePositionFront];
    
    self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
    self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
    [self.imageOutput setOutputSettings:@{AVVideoCodecKey : AVVideoCodecJPEG}];
    
    self.session = [[AVCaptureSession alloc] init];
    
    self.session.sessionPreset = AVCaptureSessionPreset1280x720;
    
    //输出输入设备结合
    if ([self.session canAddInput:self.input]) {
        
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.imageOutput]) {
        
        [self.session addOutput:self.imageOutput];
    }
    
    //预览层的生成
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    
    //设备开始取景
    [self.session startRunning];
    
    if ([_device lockForConfiguration:nil]) {
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}


/**设置为前置摄像头*/
- (AVCaptureDevice *)camearWithPosition:(AVCaptureDevicePosition)position{
    
    NSArray *mediaTypes = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    
    for (AVCaptureDevice *device in mediaTypes) {
        
        if (device.position == position) {
            
            return device;
        }
    }
    
    return nil;
}

/**切换前后摄像头*/
- (void)switchCameraAction:(id)sender{
    
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    
    if (cameraCount > 1) {
        
        NSError *error;
        
        //添加翻转动画
        CATransition *animation = [CATransition animation];
        animation.duration = 0.5;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = @"oglFlip";
        
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        
        //拿到另外一个摄像头位置
        AVCaptureDevicePosition position = [[_input device] position];
        if (position == AVCaptureDevicePositionFront){
            
            newCamera = [self camearWithPosition:AVCaptureDevicePositionBack];
            
            animation.subtype = kCATransitionFromLeft;//动画翻转方向
        }else{
            
            newCamera = [self camearWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;
        }
        
        //生成新的输入
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:&error];
        [self.previewLayer addAnimation:animation forKey:nil];
        
        if (newInput != nil) {
            
            [self.session beginConfiguration];
            [self.session removeInput:self.input];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
                self.input = newInput;
                
            } else {
                [self.session addInput:self.input];
            }
            [self.session commitConfiguration];

        }else if (error){
            
            NSLog(@"toggle carema failed, error = %@", error);

        }
    }
    
}

/**拍照*/
- (void)takePhotoAction:(id)sender{
    
    AVCaptureConnection *connection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    
    if (!connection) {
        
        NSLog(@"拍照失败!");
        return;
    }
    
    
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        
        if (imageDataSampleBuffer == nil) return;
        
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        
        
        UIImage *image = [UIImage imageWithData:imageData];
        
        
        UIView *clearView = _customPhotoView.clear;
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.frame = clearView.frame;
        imageView.clipsToBounds = YES;
        [self.view addSubview:imageView];
        
        [self.session stopRunning];
        

        
//        CGRect rect =  CGRectMake(self.view.frame.origin.x*scale, self.view.frame.origin.y*scale, self.view.frame.size.width*scale, self.view.frame.size.height*scale); //要裁剪的图片区域，按照原图的像素大小来，超过原图大小的边自动适配
//        CGImageRef cgimg = CGImageCreateWithImageInRect([image3 CGImage], rect);
//        image3 = [UIImage imageWithCGImage:cgimg];
        
        [self dismissViewControllerAnimated:NO completion:^{
            
            self.block(image);
        }];
        

    }];
}




#pragma mark -获取焦点
- (void)focusGesture:(UITapGestureRecognizer *)gesture{
    
    CGPoint point = [gesture locationInView:gesture.view];
    
    [self focusAtPoint:point];
}

- (void)focusAtPoint:(CGPoint)point{
    
    CGSize size = self.view.bounds.size;
    CGPoint focusPoint = CGPointMake(point.y / size.height, 1 - point.x/size.width);
    NSError *error;
    
    if ([self.device lockForConfiguration:&error]) {
        
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        
        if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
            [self.device setExposurePointOfInterest:focusPoint];
            [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [self.device unlockForConfiguration];
        
        self.focusView.center = point;
        self.focusView.hidden = NO;
        
        [UIView animateWithDuration:0.3 animations:^{
            _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                _focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                _focusView.hidden = YES;
            }];
        }];
        
    }else{
    
        NSLog(@"error:%@",error);
    }
}

@end
